{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'\\xd6\\xd0'"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"中\".encode(\"gbk\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'中'"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b'\\xd6\\xd0'.decode(\"gbk\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'\\xe4\\xb8\\xad'"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"中\".encode(\"utf-8\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "ename": "UnicodeDecodeError",
     "evalue": "'gbk' codec can't decode byte 0xad in position 2: incomplete multibyte sequence",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m------\u001b[0m",
      "\u001b[0;31mUnicodeDecodeError\u001b[0mTraceback (most recent call last)",
      "\u001b[0;32m<ipython-input-79-263e18e1ef1c>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34mb'\\xe4\\xb8\\xad'\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdecode\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"gbk\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mUnicodeDecodeError\u001b[0m: 'gbk' codec can't decode byte 0xad in position 2: incomplete multibyte sequence"
     ]
    }
   ],
   "source": [
    "b'\\xe4\\xb8\\xad'.decode(\"gbk\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: './notfound'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0mTraceback (most recent call last)",
      "\u001b[0;32m<ipython-input-92-2200ec23e005>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# 读文件\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"./notfound\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmode\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"r\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"close file\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: './notfound'"
     ]
    }
   ],
   "source": [
    "# 读文件\n",
    "f = open(\"./notfound\", mode = \"r\")\n",
    "print(f.read())\n",
    "print(\"close file\")\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [],
   "source": [
    "#写文件\n",
    "f = open(\"./test1.txt\", mode = \"a\", encoding=\"utf-8\")\n",
    "f.write(\"中\\n\")\n",
    "f.write(\"编程小妙招，Python 学两招\")\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "close file\n"
     ]
    },
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: './notfound.txt'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0mTraceback (most recent call last)",
      "\u001b[0;32m<ipython-input-93-c948730b8828>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m#读文件，记得关闭文件\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m     \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"./notfound.txt\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      4\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: './notfound.txt'"
     ]
    }
   ],
   "source": [
    "#读文件，记得关闭文件\n",
    "try:\n",
    "    f = open(\"./notfound.txt\")\n",
    "    print(f.read())\n",
    "\n",
    "finally:\n",
    "    print(\"close file\")\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: './notfound.txt'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0mTraceback (most recent call last)",
      "\u001b[0;32m<ipython-input-94-77405ef8e775>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"./notfound.txt\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmode\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"r\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mreader\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mreader\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: './notfound.txt'"
     ]
    }
   ],
   "source": [
    "with open(\"./notfound.txt\", mode=\"r\") as reader:\n",
    "    print(reader.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "this is a test file\n",
      "这是一个测试文件\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from contextlib import suppress\n",
    "with suppress(FileNotFoundError):\n",
    "    with open(\"./found.txt\", mode=\"r\") as reader:\n",
    "        print(reader.read())\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "this is a test file\n",
      "这是一个测试文件\n",
      "\n"
     ]
    }
   ],
   "source": [
    "with open(\"./found.txt\", mode=\"r\", encoding=\"utf-8\", errors=\"ignore\") as reader:\n",
    "    print(reader.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "method 1:\n",
      "this is a test file\n",
      "这是一个测试文件\n",
      "method 2:\n",
      "this is a test file\n",
      "这是一个测试文件\n"
     ]
    }
   ],
   "source": [
    "#如果文件比较大\n",
    "\n",
    "print(\"method 1:\")\n",
    "with open(\"./found.txt\", mode=\"r\") as reader:\n",
    "    for line in reader:\n",
    "        print(line.strip())\n",
    "        \n",
    "print(\"method 2:\")\n",
    "with open(\"./found.txt\", mode=\"r\") as reader:\n",
    "    for line in reader.readlines():\n",
    "        print(line.strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "method 3:\n",
      "this is a test file\n",
      "这是一个测试文件\n"
     ]
    }
   ],
   "source": [
    "print(\"method 3:\")\n",
    "read_size = 5\n",
    "with open(\"./found.txt\", mode=\"r\") as reader:    \n",
    "    while True:        \n",
    "        str1 = reader.read(read_size)\n",
    "        if not str1:\n",
    "            #未读取到数据，说明已经读完，退出循环\n",
    "            break\n",
    "        #消费读到的内容\n",
    "        print(str1, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 读写文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "19"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f = open('workfile', 'rb+')\n",
    "f.write('0123456789abcdef中'.encode())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "19"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f.tell()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "b'5'"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# f.seek(offset, whence) 可以改变文件对象的位置。\n",
    "# whence = 0 从文件开头，默认\n",
    "# whence = 2 从文件末尾移动\n",
    "# whence = 1 从文件当前位置移动\n",
    "\n",
    "f.seek(5) #指针移动到第六个字节\n",
    "print(f.tell())\n",
    "f.read(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f.tell()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'\\xe4'"
      ]
     },
     "execution_count": 114,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f.seek(-3, 2)  # 二进制模式\n",
    "f.read(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# json 的序列化和反序列化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "json 序列化：Python 对象转化为 json 字符串\n",
      "type(params_str) = <class 'str'>\n",
      "params_str = '{\"symbol\": \"123456\", \"type\": \"limit\", \"price\": 123.4, \"amount\": 23}'\n",
      "json 反序列化：json 字符串转化为 Python 对象\n",
      "type(original_params) = <class 'dict'>\n",
      "original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "params = {\n",
    "    'symbol': '123456',\n",
    "    'type': 'limit',\n",
    "    'price': 123.4,\n",
    "    'amount': 23\n",
    "}\n",
    "\n",
    "params_str = json.dumps(params)\n",
    "\n",
    "print('json 序列化：Python 对象转化为 json 字符串')\n",
    "print(f'{type(params_str) = }\\n{params_str = }')\n",
    "\n",
    "original_params = json.loads(params_str)\n",
    "\n",
    "print('json 反序列化：json 字符串转化为 Python 对象')\n",
    "print(f'{type(original_params) = }\\n{original_params = }')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "json 序列化：Python 对象转化为 json 字符串\n",
      "{\"symbol\": \"123456\", \"type\": \"limit\", \"price\": 123.4, \"amount\": 23}\n",
      "json 反序列化：json 字符串转化为 Python 对象\n",
      "type(original_params) = <class 'dict'>\n",
      "original_params = {'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "params = {\n",
    "    'symbol': '123456',\n",
    "    'type': 'limit',\n",
    "    'price': 123.4,\n",
    "    'amount': 23\n",
    "}\n",
    "\n",
    "with open('params.json', 'w') as writer:\n",
    "    json.dump(params, writer)\n",
    "\n",
    "print('json 序列化：Python 对象转化为 json 字符串')\n",
    "\n",
    "!cat params.json\n",
    "    \n",
    "with open('params.json', 'r') as reader:\n",
    "    original_params = json.load(reader)\n",
    "    \n",
    "print('\\njson 反序列化：json 字符串转化为 Python 对象')\n",
    "print(f'{type(original_params) = }\\n{original_params = }')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 对象的序列化和反序列化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Myclass: \n",
    "    name = 'somenzz'\n",
    "    language = 'python'\n",
    "    def __str__(self):\n",
    "        return f\"Myclass<name = {self.name} language = {self.language}>\"\n",
    "x = Myclass()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [],
   "source": [
    "pickle.dump(x,open(\"data.pkl\",\"wb\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "�\u0004�\u001b\u0000\u0000\u0000\u0000\u0000\u0000\u0000�\b__main__��\u0007Myclass���)��."
     ]
    }
   ],
   "source": [
    "!cat data.pkl"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pickle.load(open(\"data.pkl\",\"rb\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Myclass<name = somenzz language = python>\n"
     ]
    }
   ],
   "source": [
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
